# gozerlib/utils/web.py
#
#

""" google auth related functions. """

## google imports

from google.appengine.api import users as gusers

def finduser():

    """ try to find the email of the current logged in user. """

    user = gusers.get_current_user()

    if user:
        return user.email()

    return "" 

def checkuser(response, request):

    """
        check for user based on web response. first try google 
        otherwise return 'notath@IP' 

        :param response: response object
        :param request: request object
        :rtype: tuple of (userhost, gmail user, gozerwave user , nick)
    """

    userhost = None
    u = None
    nick = None
    user = gusers.get_current_user()

    if not user:

        try:
            email = request.environ['USER_EMAIL']

            if email:
                userhost = nick = "%s!%s" % (request.remote_addr, email)
            else:
                userhost = nick = "notauth@%s" % request.remote_addr

        except KeyError:
            userhost = nick = "notauth@%s" % request.remote_addr
    else:
        userhost = user.email() 

        if not userhost:
            userhost = nick = "notauth@%s" % request.remote_addr

        nick = user.nickname()

    u = userhost
    return (userhost, user, u, nick)
